<?php

namespace App\Http\Controllers\Member;

use App\Constants\ResponseArray;
use App\Http\Controllers\BaseController;
use App\Http\Services\Member\MemberService;
use App\Models\Member;
use App\Models\MemberImage;
use App\Models\MemberRequest;
use App\Models\MemberThumbsUp;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class MemberController extends BaseController
{

    public function memberList(Request $request)
    {
        $userInfo = auth('a')->user();
        if (!$userInfo)
        {
            return ResponseArray::unauthenticatedError();
        }
        $data = $request->all();

        if (empty($userInfo['member']['sex']))
        {
            return ResponseArray::renderError('请您先设置性别.');
        }
        $needSex = $userInfo['member']['sex'] == '1' ? 2 : 1;
        //logger('收到请求地址memberList : ' . $request->path() . json_encode($data) );
        $rules = [
            'key_word' => 'nullable|string',
            'is_favorite' => 'nullable',
            'is_thumbs_up' => 'nullable',
        ];
        $result = $this->validator($data, $rules, []);
        if ($result) {
            return ResponseArray::parameterError($result, $rules);
        }

        $perPage = intval($request->input('per_page',10));


        $model = Member::query()->where([
                ['sex',$needSex],

        //      用户审核机制
        //      ['is_audit',1],

            ]);

        if (!empty($data['age_min_request']))
        {
            $model->where('age','>=',$data['age_min_request']);
        }

        if (!empty($data['age_max_request']))
        {
            $model->where('age','<=',$data['age_max_request']);
        }

        if (!empty($data['height_min_request']))
        {
            $model->where('height','>=',$data['height_min_request']);
        }

        if (!empty($data['height_max_request']))
        {
            $model->where('height','<=',$data['height_max_request']);
        }

        if (!empty($data['education_background_code_request']))
        {
            $model->where('education_background_code','>=',$data['education_background_code_request']);
        }

        if (!empty($data['annual_income_request']))
        {
            $model->where('annual_income',$data['annual_income_request']);
        }

        if (!empty($data['annual_income_min_request']))
        {
            $model->where('annual_income_min','>=',$data['annual_income_min_request']);
        }

        if (!empty($data['asset_house_request']))
        {
            if (is_array($data['asset_house_request']))
            {
                $model->whereIn('asset_house',$data['asset_house_request']);
            }else{
                $model->where('asset_house',$data['asset_house_request']);
            }
        }

        if (!empty($data['asset_car_request']))
        {
            $model->where('asset_car',$data['asset_car_request']);
        }

        if (!empty($data['marital_status_request']))
        {
            if (is_array($data['marital_status_request']))
            {
                $model->whereIn('marital_status',$data['marital_status_request']);
            }else{
                $model->where('marital_status',$data['marital_status_request']);
            }
        }

        if (!empty($data['want_child_request']))
        {
            $model->where('want_child',$data['want_child_request']);
        }

        if (!empty($data['key_word']))
        {
            $model->where(function($q)use($data){
                $q->where('nick_name','like','%' . $data['key_word'] . '%')
                    ->orWhere('id',$data['key_word']);
            });
        }
        if (!empty($data['is_favorite']))
        {
            $model->whereHas('member_favorite_to_member',function($q)use($userInfo){
                $q->where('member_id',$userInfo['member']['id']);
            });
        }
        if (!empty($data['is_thumbs_up']))
        {
            $model->whereHas('member_thumbs_up_to_member',function($q)use($userInfo){
                $q->where('member_id',$userInfo['member']['id']);
            });
        }
        $res = $model->with(['member_image'])
            ->paginate($perPage);

        $res = $res->toArray();
        unset($res['links']);

        return ResponseArray::response($res,'会员列表获取成功.');
    }

    public function memberDetail(Request $request)
    {
        $userInfo = auth('a')->user();
        if (!$userInfo)
        {
            return ResponseArray::unauthenticatedError();
        }
        $data = $request->all();
        $rules = [
            'id' => 'required|string',
        ];
        $result = $this->validator($data, $rules, []);
        if ($result) {
            return ResponseArray::parameterError($result, $rules);
        }

        $res = Member::query()
            ->with(['member_image'])
            ->with(['member_thumbs_up_to_member' => function($q)use($userInfo){
                $q->where('member_id',$userInfo['member']['id']);
            }])
            ->with(['member_favorite_to_member' => function($q)use($userInfo){
                $q->where('member_id',$userInfo['member']['id']);
            }])
            ->with(['member_request' => function($q){
                $q->select(MemberRequest::columns(0));
            }])
            ->findOrFail($data['id']);

        return ResponseArray::response($res ? $res->toArray()  : [] ,'会员详情获取成功.');
    }

    public function receiveMyThumbsUpList(Request $request)
    {
        $userInfo = auth('a')->user();
        if (!$userInfo)
        {
            return ResponseArray::unauthenticatedError();
        }
        $data = $request->all();
        $rules = [
            'id' => 'nullbale|string',
            'key_word' => 'nullable|string',
        ];
        $result = $this->validator($data, $rules, []);
        if ($result) {
            return ResponseArray::parameterError($result, $rules);
        }
        $perPage = intval($request->input('per_page',10));

        $thumbsUpCount = MemberThumbsUp::query()
            ->where('to_member_id',$userInfo['member']['id'])
            ->count();

        $model = MemberThumbsUp::query()
            ->where('to_member_id',$userInfo['member']['id']);

        if (!empty($data['key_word']))
        {
            $model->whereHas('member',function($q)use($data){
                $q->where('nick_name','like','%' . $data['key_word']. '%');
            });
        }

        $model->with(['member']);

        $model->orderBy('created_at','desc');

        $res = $model->paginate($perPage);

        $res = $res->toArray();

        unset($res['links']);

        $res['thumbs_up_count'] = $thumbsUpCount;

        return ResponseArray::response($res ,'收到的点赞列表获取成功.');
    }

    public function save(Request $request)
    {
        $data = $request->all();
        $rules = [
            'id' => 'required|string',
        ];
        $result = $this->validator($data, $rules, []);
        if ($result) {
            return ResponseArray::parameterError($result, $rules);
        }

        unset($data['age'],$data['education_background_code'],$data['annual_income_min'],$data['annual_income_max']);
        if (isset($data['birth_day']) && $data['birth_day'] !== '')
        {

            $now = Carbon::now();

            // 创建一个新的 Carbon 对象表示出生日期
            $birthdate = new Carbon($data['birth_day']); // YYYY-MM-DD 应该被替换成真正的出生日期

            // 计算两个日期之间相差的年数
            $age = $now->diffInYears($birthdate);

            $data['age'] = $age;
        }

        if (array_key_exists('education_background',$data) )
        {
            $data['education_background_code'] = Member::Education_Background_Map[$data['education_background']] ?? null;
        }

        if (array_key_exists('annual_income',$data) )
        {
            $incomeRange = Member::Annual_Income_Map[$data['annual_income']] ?? [];
            $data['annual_income_min'] = $incomeRange[0] ?? null;
            $data['annual_income_max'] = $incomeRange[1] ?? null;
        }

        $member = Member::query()->findOrFail($data['id']);

        if ($data['profile_photo'] && $data['profile_photo'] != $member->profile_photo)
        {
            $data['upload_profile_photo'] = $data['profile_photo'];
            $data['profile_photo'] = env('AUDIT_DISPLAY_PIC',null);
        }
        DB::beginTransaction();

        $res = Member::saveEntity($data);

        if (!empty($data['member_request']))
        {
            $data['member_request']['member_id'] = $res['id'];
            MemberRequest::saveEntity($data['member_request']);
        }

        if (!empty($data['member_image']))
        {
            $existedIds = array_column($data['member_image'],'id');

            MemberImage::query()
                ->where('member_id' , $data['id'])
                ->whereNotIn('id',$existedIds)
                ->delete();

            $newMemberImageInsert = [];
            foreach($data['member_image'] as $imageArr)
            {
                if (empty($imageArr['id']))
                {
                    $newMemberImageInsert[] = [
                        'member_id'  => $data['id'],
                        // 图片审核机制,默认展示审核中图片
                        //'url'        => env('AUDIT_DISPLAY_PIC',null),
                        'url'        => $imageArr['url'],
                        'upload_url' => $imageArr['url'],
                        'is_audit'   => 0,
                        'created_at' => time(),
                    ];
                }
            }
            if (!empty($newMemberImageInsert))
            {
                MemberImage::query()->insert($newMemberImageInsert);
            }
        }

        DB::commit();

        return ResponseArray::response($res ? $res->toArray()  : [] ,'我的信息保存成功.');
    }

    public function updateMyFavorite(Request $request)
    {
        $data = $request->all();

        $rules = [
            'to_member_id' => 'required',
            'is_favorite'  => 'required|in:0,1',
        ];

        $result = $this->validator($data, $rules, []);
        if ($result) {
            return ResponseArray::parameterError($result, $rules);
        }
        $userInfo = auth('a')->user();
        if (!$userInfo)
        {
            return ResponseArray::unauthenticatedError();
        }
        if ($data['to_member_id'] == $userInfo['member']['id'])
        {
            return ResponseArray::renderError('无法将自己加入收藏夹.',false);
        }

        $res = MemberService::updateMyFavorite($userInfo['member']['id'],$data['to_member_id'],$data['is_favorite']);

        if (!$res)
        {
            return ResponseArray::renderError('更新收藏失败,请重新尝试.',false);
        }

        return ResponseArray::response(true,'更新收藏夹成功.');
    }

    public function updateMyThumbsUp(Request $request)
    {
        $data = $request->all();

        $rules = [
            'to_member_id' => 'required',
            'is_thumbs_up'  => 'required|in:0,1',
        ];

        $result = $this->validator($data, $rules, []);
        if ($result) {
            return ResponseArray::parameterError($result, $rules);
        }
        $userInfo = auth('a')->user();
        if (!$userInfo)
        {
            return ResponseArray::unauthenticatedError();
        }
        if ($data['to_member_id'] == $userInfo['member']['id'])
        {
            return ResponseArray::renderError('无法给自己点赞.',false);
        }

        $res = MemberService::updateMyThumbsUp($userInfo['member']['id'],$data['to_member_id'],$data['is_thumbs_up']);

        if (!$res)
        {
            return ResponseArray::renderError('更新点赞失败,请重新尝试.',false);
        }

        return ResponseArray::response(true,'更新点赞成功.');
    }

}

